package services

import (
	"fmt"
	"stacks/database"
	"stacks/models"
)

// MenuService 菜单服务
type MenuService struct{}

// NewMenuService 创建菜单服务实例
func NewMenuService() *MenuService {
	return &MenuService{}
}

// CreateDefaultMenus 创建默认菜单数据
func (s *MenuService) CreateDefaultMenus(tenantID uint) error {
	// 定义默认菜单数据
	defaultMenus := []models.SysMenu{
		// 仪表板菜单
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "dashboard",
			Path:        "/dashboard",
			Component:   "LAYOUT",
			Redirect:    "/dashboard/base",
			ParentID:    0,
			Icon:        "dashboard",
			Title:       "仪表板",
			TitleEn:     "Dashboard",
			Sort:        1,
			OrderNo:     100,
			Status:      1,
		},
		// 仪表板 - 基础
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "dashboard-base",
			Path:        "base",
			Component:   "/dashboard/base/index",
			ParentID:    1,
			Title:       "基础仪表板",
			TitleEn:     "Base Dashboard",
			Sort:        1,
			Status:      1,
		},
		// 仪表板 - 详情
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "dashboard-detail",
			Path:        "detail",
			Component:   "/dashboard/detail/index",
			ParentID:    1,
			Title:       "详情仪表板",
			TitleEn:     "Detail Dashboard",
			Sort:        2,
			Status:      1,
		},
		// 列表页菜单
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "list",
			Path:        "/list",
			Component:   "LAYOUT",
			Redirect:    "/list/base",
			ParentID:    0,
			Icon:        "view-list",
			Title:       "列表页",
			TitleEn:     "List",
			Sort:        2,
			OrderNo:     200,
			Status:      1,
		},
		// 列表页 - 基础
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "list-base",
			Path:        "base",
			Component:   "/list/base/index",
			ParentID:    4,
			Title:       "基础列表页",
			TitleEn:     "Base List",
			Sort:        1,
			Status:      1,
		},
		// 列表页 - 卡片
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "list-card",
			Path:        "card",
			Component:   "/list/card/index",
			ParentID:    4,
			Title:       "卡片列表页",
			TitleEn:     "Card List",
			Sort:        2,
			Status:      1,
		},
		// 表单页菜单
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "form",
			Path:        "/form",
			Component:   "LAYOUT",
			Redirect:    "/form/base",
			ParentID:    0,
			Icon:        "edit-1",
			Title:       "表单页",
			TitleEn:     "Form",
			Sort:        3,
			OrderNo:     300,
			Status:      1,
		},
		// 表单页 - 基础
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "form-base",
			Path:        "base",
			Component:   "/form/base/index",
			ParentID:    7,
			Title:       "基础表单页",
			TitleEn:     "Base Form",
			Sort:        1,
			Status:      1,
		},
		// 详情页菜单
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "detail",
			Path:        "/detail",
			Component:   "LAYOUT",
			Redirect:    "/detail/base",
			ParentID:    0,
			Icon:        "layers",
			Title:       "详情页",
			TitleEn:     "Detail",
			Sort:        4,
			OrderNo:     400,
			Status:      1,
		},
		// 详情页 - 基础
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "detail-base",
			Path:        "base",
			Component:   "/detail/base/index",
			ParentID:    10,
			Title:       "基础详情页",
			TitleEn:     "Base Detail",
			Sort:        1,
			Status:      1,
		},
		// 系统管理菜单
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "system",
			Path:        "/system",
			Component:   "LAYOUT",
			Redirect:    "/system/user",
			ParentID:    0,
			Icon:        "setting",
			Title:       "系统管理",
			TitleEn:     "System Management",
			Sort:        5,
			OrderNo:     500,
			Status:      1,
		},
		// 用户管理菜单
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "user",
			Path:        "user",
			Component:   "/system/user/index",
			ParentID:    13,
			Icon:        "user",
			Title:       "用户管理",
			TitleEn:     "User Management",
			Sort:        1,
			Status:      1,
		},
		// 角色管理菜单
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "role",
			Path:        "role",
			Component:   "/system/role/index",
			ParentID:    13,
			Icon:        "usergroup",
			Title:       "角色管理",
			TitleEn:     "Role Management",
			Sort:        2,
			Status:      1,
		},
		// 权限管理菜单
		{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        "permission",
			Path:        "permission",
			Component:   "/system/permission/index",
			ParentID:    13,
			Icon:        "security",
			Title:       "权限管理",
			TitleEn:     "Permission Management",
			Sort:        3,
			Status:      1,
		},
	}

	db := database.GetDB()

	// 创建菜单数据
	for i := range defaultMenus {
		err := db.FirstOrCreate(&defaultMenus[i], models.SysMenu{
			TenantModel: models.TenantModel{TenantID: tenantID},
			Name:        defaultMenus[i].Name,
		}).Error
		if err != nil {
			return fmt.Errorf("创建菜单 %s 失败: %v", defaultMenus[i].Name, err)
		}
	}

	return nil
}

// GetUserMenus 获取用户菜单
func (s *MenuService) GetUserMenus(userID uint) ([]models.SysMenu, error) {
	var menus []models.SysMenu

	// 对于多表JOIN查询，使用原始数据库实例，避免过滤器问题
	db := database.GetRawDB()

	// 使用一次性JOIN查询，手动添加删除条件
	err := db.
		Select("DISTINCT m.*").
		Table("sys_menu m").
		Joins("JOIN sys_permission p ON p.path = m.path AND p.type = 1 AND p.delete_at IS NULL").
		Joins("JOIN sys_role_permission rp ON rp.permission_id = p.id AND rp.delete_at IS NULL").
		Joins("JOIN sys_user_role ur ON ur.role_id = rp.role_id AND ur.delete_at IS NULL").
		Where("ur.user_id = ? AND m.status = 1 AND m.delete_at IS NULL", userID).
		Order("m.order_no ASC").
		Find(&menus).Error

	if err != nil {
		return nil, err
	}

	if len(menus) == 0 {
		return menus, nil
	}

	// 获取需要显示的菜单ID（包括父菜单）
	permittedMenuIDs := make(map[uint]bool)
	for _, menu := range menus {
		permittedMenuIDs[menu.ID] = true
		// 包含父菜单
		if menu.ParentID != 0 {
			permittedMenuIDs[menu.ParentID] = true
		}
	}

	// 对于单表查询，使用带过滤器的数据库实例
	dbWithFilter := database.GetDB()

	// 查询所有需要显示的菜单（包括父菜单）
	var filteredMenus []models.SysMenu
	err = dbWithFilter.Where("id IN ?", getKeys(permittedMenuIDs)).Order("order_no ASC").Find(&filteredMenus).Error
	if err != nil {
		return nil, err
	}

	return filteredMenus, nil
}

// getKeys 从map中获取所有key
func getKeys(m map[uint]bool) []uint {
	keys := make([]uint, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	return keys
}
